<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ this.$router.currentRoute.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表卡片区 -->
    <el-card class="box-card">

      <el-page-header @back=""
                      :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>

      <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form"  size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item>
          <el-select
              style="width: 140px;"
              placeholder="请选择账号"
              v-model="queryMap.accountName"
              @change="search"
              filterable
          >
            <el-option
                v-for="(name) in accountName"
                :key="name"
                :label="name"
                :value="name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" icon="el-icon-search"  @click="search()">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="multipleTable" size="small" :data="userList" border style="width: 70.8%;margin-top: 2vh"
                height="600">
        <el-table-column prop="nickName" label="昵称" width="150"></el-table-column>
        <el-table-column prop="userName" label="用户名" width="150"></el-table-column>
        <el-table-column prop="resourceCount" label="资源数" width="150"></el-table-column>
        <el-table-column prop="clientCount" label="客户数" width="150"></el-table-column>
        <el-table-column width="280" label="操作">
          <template v-slot="scope">
            <el-tooltip content="资源回收" placement="top" effect="light">
              <el-button circle round plain v-hasPermission="''" size="small" type="primary" icon="el-icon-refresh"
                         @click="openForm(scope.row.userId,1)"></el-button>
            </el-tooltip>
            <el-tooltip content="客户回收" placement="top" effect="light">
              <el-button circle round plain v-hasPermission="''" size="small" type="primary"
                         icon="el-icon-refresh-right" @click="openForm(scope.row.userId,2);"></el-button>
            </el-tooltip>
            <el-tooltip content="资源分配" placement="top" effect="light">
              <el-button circle round plain v-hasPermission="''" size="small" type="primary" icon="el-icon-bottom-left"
                         @click="resourceShiftProcess(scope.row.userId,1)"></el-button>
            </el-tooltip>
            <el-tooltip content="客户分配" placement="top" effect="light">
              <el-button circle round plain v-hasPermission="''" size="small" type="primary" icon="el-icon-bottom-right"
                         @click="resourceShiftProcess(scope.row.userId,2)"></el-button>
            </el-tooltip>
            <el-tooltip content="资源删除" placement="top" effect="light">
              <el-button circle round plain v-hasPermission="''" size="small" type="primary" icon="el-icon-delete-solid"
                         @click="deleteResourceProcess(scope.row.userId,1)"></el-button>
            </el-tooltip>
            <el-tooltip content="客户删除" placement="top" effect="light">
              <el-button circle round plain v-hasPermission="''" size="small" type="primary" icon="el-icon-delete"
                         @click="deleteResourceProcess(scope.row.userId,2)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
          :title="formLabel"
          :visible.sync="dialogVisible"
          width="30%"
      >
        <!-- 输入表单 -->
        <el-form :model="taskPackageForm"><el-form-item label="选择账号:">
          <el-select
              style="width: 240px;"
              v-model="queryMap.addAccountName"
              filterable
              placeholder="请选择账号"
              @change="accountNameChange"
          >
            <el-option
                v-for="(name) in accountName"
                :key="name"
                :label="name"
                :value="name">
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="归属人">
            <el-select v-model="addTask.newUserId" style="width: 250px;" filterable placeholder="请选择归属人">
              <el-option
                  v-for="item in tableData"
                  :key="item.userId"
                  :label="item.userName + '('+ item.nickName +')'"
                  :value="item.userId">
              </el-option>
            </el-select>
            <span style="color: red"> *</span>
          </el-form-item>
          <el-form-item :label="formLabel">
            <el-input
                v-model="taskPackageForm.taskPackageName"
                :placeholder="'请输入新建任务包名称'"
                clearable
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="handleConfirm"
                   :loading="btnLoading"
                   :disabled="btnDisabled"
        >确 定</el-button>
      </span>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
      <!-- 选择用户窗口 -->
      <ElectUsersBox title="资源分配" @confirmUserId="confirmUserId" :isShow="electUsersBoxShow"
                     @updateElectUsersBoxShow="electUsersBoxShow=false"/>
    </el-card>
  </div>
</template>
<script>

import ElectUsersBox from "../../../components/electUsersBox.vue";

export default {
  components: {ElectUsersBox},
  data() {
    return {
      btnLoading: false,
      btnDisabled: false,
      dialogVisible: false,
      formLabel: '回收资源',
      openDialog: "resourceRecycling",
      tableData: [],
      addTask: {
        oldUserId: null,
        newUserId: null,
      },
      taskPackageForm: {
        taskPackageName: ''
      },
      electUsersBoxShow: false,
      total: 0,
      accountName:[],//账号
      userList: [],
      resourceIds: null,
      queryMap: {
        pageNum: 1,
        pageSize: 10,
        accountName:'',
        addAccountName:'',
      },
    };
  },
  methods: {
    //重置
    reset(){
      this.queryMap={
        pageNum: 1,
        pageSize: 10,
        accountName:'',
      }
      this.getUserList();
    },
    //资源转移
    resourceShiftProcess(userId, openType) {
      if (openType === 1) {
        this.resourceIds = this.getResourceIdByUserId(userId);
      } else if (openType === 2) {
        this.resourceIds = this.getClientIdByUserId(userId);
      }
      this.electUsersBoxShow = true;
    },
    //删除选择
    deleteResourceProcess(userId, openType) {
      if (openType === 1) {
        this.resourceIds = this.getResourceIdByUserId(userId);
        this.deleteResource();
      } else if (openType === 2) {
        this.resourceIds = this.getClientIdByUserId(userId);
        this.deleteResource();
      }
    },
    //弹窗选择
    confirmUserId(ids) {
      if (!ids || ids.length === 0) {
        this.$message('未选择用户');
        return;
      }
      this.resourceShift(this.resourceIds, ids);
    },
    //资源、客户转移
    async resourceShift(resourceIds, userIds) {
      const confirmResult = await this.$confirm('确认要分配吗？此操作不可恢复，请谨慎操作', '分配提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消分配操作');
      })
      if (confirmResult) {
        const {data: res} = await this.$http.put("/outUser/clientShift", {
          resourceIds: resourceIds,
          userIds: userIds
        });
        if (res > 0) {
          await this.getUserList();
          this.$message.success(`分配成功，共成功 ${res} 个客户`);
        } else {
          this.$message.error('分配失败，没有客户被成功分配');
        }
      }
    },
    //根据id查询资源id信息
    async getResourceIdByUserId(userId) {
      try {
        const {data: res} = await this.$http.get("outUser/getResourceIdByUserId", {
          params: {userId: userId}  // 正确传递参数
        });

        // 确保数据正确赋值
        if (res && Array.isArray(res)) {
          this.resourceIds = res;
        } else {
          console.error("返回数据格式不正确:", res);
        }
      } catch (error) {
        console.error("获取资源 ID 失败:", error);
      }
    },
    //根据id查询客户id信息
    async getClientIdByUserId(userId) {
      try {
        const {data: res} = await this.$http.get("outUser/getClientIdByUserId", {
          params: {userId: userId}  // 正确传递参数
        });
        // 确保数据正确赋值
        if (res && Array.isArray(res)) {
          this.resourceIds = res;
        } else {
          console.error("返回数据格式不正确:", res);
        }
      } catch (error) {
        console.error("获取资源 ID 失败:", error);
      }
    },
    //批量删除客户
    async deleteResource() {
      // 弹出确认框，询问用户是否确认删除
      const confirmResult = await this.$confirm('确认要删除？此操作不可恢复，请谨慎操作', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消删除操作');
      })
      if (confirmResult) {
        // 发送批量删除请求
        const response = await this.$http.put("outUser/deleteResource", {
              resourceIds: this.resourceIds
            }
        )
        if (response.data.data > 0) {
          this.$message.success(`删除成功，共成功删除 ${response.data.data} 个客户`);
          // 更新列表或执行其他操作
          this.getUserList();
        } else {
          this.$message.error('删除失败，没有客户被成功删除');
        }
      }
    },
    search(){
      this.queryMap.pageNum = 1;
      this.getUserList();
    },
    //加载用户信息
    async getUserList() {
      const {data: res} = await this.$http.get(
          "outUser/selectOutUserList",
          {
            params: this.queryMap
          }
      );
      if (!res.success) {
        return this.$message.error("获取用户列表失败:" + res.data);
      } else {
        this.total = res.data.total;
        this.userList = res.data.rows;
        console.log(this.userList)
      }
    },
    /**
     * 加载用户列表
     */
    async selectUser() {
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/", {
        accountName : this.queryMap.addAccountName
      });
      if (res.success) {
        this.tableData = res.data;
      } else {
        return this.$message.error("用户列表查询失败:" + res.message);
      }
    },
    openForm(userId, count) {
      this.addTask.oldUserId = userId;
      this.dialogVisible = true;
      this.taskPackageForm.taskPackageName = '';
      if (count === 1) {
        this.formLabel = '回收资源';
        this.openDialog = 'resourceRecycling';
      }else {
        this.formLabel = '回收客户';
        this.openDialog = 'customerRecycling';
      }
    },
    handleConfirm() {
      if (this.openDialog === 'resourceRecycling') {
        this.resourceRecycling();
      } else if (this.openDialog === 'customerRecycling') {
        this.customerRecycling();
      }
    },
    async resourceRecycling(){
      if (!this.taskPackageForm.taskPackageName) {
        this.$message.error("请输入任务包名称");
        return;
      }
      this.btnLoading = true;
      this.btnDisabled = true;
      // 弹出确认框，询问用户是否确认回收
      const confirmResult = await this.$confirm('请确认输入的名称，及回收操作', '回收提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消回收操作');
      })
      if (confirmResult) {
        // 创建 FormData 对象
        const formData = new FormData();
        // 将参数添加到 FormData 对象中
        formData.append("taskPackageName", this.taskPackageForm.taskPackageName);
        formData.append("oldUserId", this.addTask.oldUserId);
        formData.append("newUserId", this.addTask.newUserId);
        // 发送批量删除请求
        const response = await this.$http.put("outUser/resourceRecycling", formData
        ).catch((error) => {
          this.$message.error('回收失败:'+error);
          this.btnLoading = false;
          this.btnDisabled = false;
        })
        if (response.data.data === "success") {
          this.$message.success(`回收成功`);
        }else if (response.data.data === "isNull") {
          this.$message.warning('回收失败，没有资源或已被成功回收');
        }else {
          console.log(response.data.data);
          this.$message.error('回收失败');
        }
        this.dialogVisible = false;
        this.btnLoading = false;
        this.btnDisabled = false;
        await this.getUserList();
      }
    },
    async customerRecycling(){
      if (!this.taskPackageForm.taskPackageName) {
        this.$message.error("请输入任务包名称");
        return;
      }
      this.btnLoading = true;
      this.btnDisabled = true;
      // 弹出确认框，询问用户是否确认回收
      const confirmResult = await this.$confirm('请确认输入的名称，及回收操作', '回收提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消回收操作');
      })
      if (confirmResult) {
        // 创建 FormData 对象
        const formData = new FormData();
        // 将参数添加到 FormData 对象中
        formData.append("taskPackageName", this.taskPackageForm.taskPackageName);
        formData.append("oldUserId", this.addTask.oldUserId);
        formData.append("newUserId", this.addTask.newUserId);
        // 发送批量删除请求
        const response = await this.$http.put("outUser/customerRecycling",formData).catch((error) => {
          this.$message.error('回收失败:'+error);
          this.btnLoading = false;
          this.btnDisabled = false;
        })
        if (response.data.data === "success") {
          this.$message.success(`回收成功`);
        }else if (response.data.data === "isNull") {
          this.$message.warning('回收失败，没有客户或已被成功回收');
        }else {
          this.$message.error('回收失败');
        }
      }
      this.dialogVisible = false;
      this.btnLoading = false;
      this.btnDisabled = false;
      await this.getUserList();
    },
    accountNameChange(){
      this.selectUser();
    },
    //改变页码
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getUserList();
    },
    //翻页
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getUserList();
    },
    /**
     * 获得账号信息
     */
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data.errorMsg);
      }
      this.accountName = res.data

    },
  },
  created() {
    this.getAccountNameList();
    this.selectUser();
    this.getUserList();
  }
};
</script>
<style scoped>
.el-radio-group {
  margin-left: 15px;
}
</style>
